package com.software.human.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.software.human.R;
import com.software.human.entity.UserInfo;
import com.software.human.util.OkHttpUtil;
import com.software.human.util.Result;

import java.io.IOException;
import java.text.ParseException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttp;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UserInfoViewActivity extends AppCompatActivity {

    private EditText edt_user_name;
    private EditText edt_user_birth;
    private EditText edt_user_weight;
    private EditText edt_user_height;
    private EditText edt_user_sex;
    private Button btn_user_save;
    // 从ListView中传递过来的UserInfo
    private UserInfo userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info_view);
        initViews();
        initEvents();
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        userInfo = intent.getSerializableExtra("userInfo", UserInfo.class);
        edt_user_name.setText(userInfo.getUserName());
        edt_user_sex.setText(userInfo.getSex());
        edt_user_birth.setText(new SimpleDateFormat("yyyy-MM-dd").format(userInfo.getBirthday()));
        edt_user_height.setText(String.valueOf(userInfo.getHeight()));
        edt_user_weight.setText(String.valueOf(userInfo.getWeight()));
    }

    private void initEvents() {
        btn_user_save.setOnClickListener(v -> {
            // 1、获得用户输入的数据
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(this.userInfo.getUserId());
            userInfo.setUserName(edt_user_name.getText().toString());
            userInfo.setSex(edt_user_sex.getText().toString());
            try {
                userInfo.setBirthday(new java.text.SimpleDateFormat("yyyy-MM-dd").parse(edt_user_birth.getText().toString()));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            userInfo.setHeight(Integer.valueOf(edt_user_height.getText().toString()));
            userInfo.setWeight(Float.valueOf(edt_user_weight.getText().toString()));
            // 2、获得传递进来的数据  this.userInfo

            // 3、比较两个数据是否相等
            if (userInfo.equals(this.userInfo)) {
                Toast.makeText(this, "数据没有发生变化", Toast.LENGTH_SHORT).show();
            } else {
                updateUserInfo(userInfo);
            }
        });

    }

    private void updateUserInfo(UserInfo userInfo) {
        String url = getString(R.string.system_url);
        OkHttpClient client = OkHttpUtil.getInstance("");
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd")
                .create();
        String json = gson.toJson(userInfo);
        RequestBody requestBody = RequestBody.create(
                json, MediaType.parse("application/json;charset=utf8")
        );
        Request request = new Request.Builder()
                .post(requestBody)
                .url(url + "/userInfo/update")
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Toast.makeText(UserInfoViewActivity.this, "更新失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String body = response.body().string();
                    Result<UserInfo> result = gson.fromJson(body, new TypeToken<Result<UserInfo>>(){}.getType());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (result.getCode() == 200) {
                                Intent intent = new Intent(
                                        UserInfoViewActivity.this,
                                        UserInfoListActivity.class
                                );
                                startActivity(intent);
                                Toast.makeText(UserInfoViewActivity.this, "更新成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(UserInfoViewActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }

            }
        });
    }

    private void initViews() {
        edt_user_name = findViewById(R.id.edt_user_name);
        edt_user_birth = findViewById(R.id.edt_user_birth);
        edt_user_sex = findViewById(R.id.edt_user_sex);
        edt_user_height = findViewById(R.id.edt_user_height);
        edt_user_weight = findViewById(R.id.edt_user_weight);
        btn_user_save = findViewById(R.id.btn_user_save);
    }
}